<template>
  <ex-dialog width="1000px" class="ex-diolog" :title="title" :visible="visible" @closeDialog="handleClose">
    <!-- <el-switch style="display: block;margin-bottom: 20px;" v-model="switchModel" :active-value="'2'" :inactive-value="'1'"
      active-color="#13ce66" inactive-color="#1890ff" active-text="开启背景" inactive-text="启用轮播图"
      @change="bannerSetShowType">
    </el-switch> -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="轮播图" name="1"></el-tab-pane>
      <!-- <el-tab-pane label="背景" name="2"></el-tab-pane> -->
    </el-tabs>
    <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm"
      v-if="activeName == '1'">
      <div>
        <div class="lable_l">
          <div class="left">轮播图</div>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </div>
        <div class="bannerBox" v-for="(item, index) in ruleForm.bannerList" :key="200 + index">
          <div class="imgBox">
            <el-form-item label="轮播图名称:" :prop="`bannerList.${index}.bannerName`" :rules="rules.bannerName">
              <el-input type="text" v-model="item.bannerName" autocomplete="off" placeholder="轮播图名称"></el-input>
            </el-form-item>
            <el-form-item label="是否显示:" :prop="`bannerList.${index}.isShow`" :rules="rules.isShow">
              <el-switch v-model="item.isShow" active-text="是" inactive-text="否" active-value="1" inactive-value="2">
              </el-switch>
            </el-form-item>
            <el-form-item label="图片:" :prop="`bannerList.${index}.imgUrl`" :rules="rules.imgUrl" ref="imgRef">
              <ImageUploadMore :limit="1" :fileSize="20" @successImg="(e) => { getBannerImg(e, index) }"
                :value="item.imgUrl">
              </ImageUploadMore>
            </el-form-item>
            <el-form-item label="跳转链接:" :prop="`bannerList.${index}.redirectType`" :rules="rules.redirectType">
              <el-radio-group v-model="item.redirectType">
                <el-radio label="1">神椰H5(含神椰小程序)</el-radio>
                <!-- <el-radio label="2">其他H5</el-radio> -->
                <!-- <el-radio label="3">小程序</el-radio> -->
              </el-radio-group>
            </el-form-item>
            <el-form-item label="APPID:" :prop="`bannerList.${index}.appId`" :rules="rules.appId"
              v-if="item.redirectType == 3">
              <el-input type="text" v-model="item.appId" autocomplete="off" placeholder="请填写APPID"></el-input>
            </el-form-item>
            <el-form-item label="链接地址:" :prop="`bannerList.${index}.redirectUrl`" :rules="rules.redirectUrl">
              <el-input type="text" v-model="item.redirectUrl" autocomplete="off" placeholder="请填写链接地址"></el-input>
            </el-form-item>
            <el-form-item label="神椰小程序链接地址:" :prop="`bannerList.${index}.wxRedirectUrl`" :rules="rules.wxRedirectUrl" v-if="item.redirectType == 1">
              <el-input type="text" v-model="item.wxRedirectUrl" autocomplete="off" placeholder="请填写链接地址"></el-input>
            </el-form-item>
            <el-form-item label="APP跳转:" :prop="`bannerList.${index}.appRedirectType`" :rules="rules.appRedirectType">
              <el-select v-model="item.appRedirectType" placeholder="请选择" size="small"
                @change="(val) => changAppRedirectType(val, index)">
                <el-option v-for="item in appTypeList" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" :prop="`bannerList.${index}.appRedirectId`" :rules="rules.appRedirectId"
              v-if="item.appRedirectType == 1 || item.appRedirectType == 2 || item.appRedirectType == 3 || item.appRedirectType == 4 || item.appRedirectType == 12 || item.appRedirectType == 13 || item.appRedirectType == 15">
              <el-select v-model="item.appRedirectId" placeholder="请选择" size="small" filterable>
                <el-option v-for="(aitem, aindex) in item.appRedirectIdList" :key="aindex" :label="aitem.value"
                  :value="aitem.id">
                </el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="rig_btn_box">
            <el-button type="primary" circle icon="el-icon-arrow-up" @click="upGo(index)" v-if="index != 0"></el-button>
            <el-button type="primary" circle icon="el-icon-arrow-down" @click="downGo(index)"
              v-if="index != ruleForm.bannerList.length - 1"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(index)"></el-button>
          </div>
        </div>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">确认</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
    <el-form :model="bjRuleForm" status-icon :rules="rules" ref="bjRuleForm" label-width="180px" class="demo-ruleForm"
      v-if="activeName == '2'">
      <div v-if="activeName == '2'">
        <el-form-item label="广告图片背景:" prop="bjImgUrl" ref="bjImgUrlRef">
          <ImageUploadMore :limit="1" :fileSize="20" :value="bjRuleForm.bjImgUrl" @successImg="getBjImg">
          </ImageUploadMore>
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitFormBj('bjRuleForm')" :loading="loading">确认</el-button>
        <el-button @click="handleClose('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </ex-dialog>
</template>
<script>
// components
import Loading from '@/components/Loading/index'
// api
import {
  adminDict,
  addBanner,
  editBanner,
  bannerInfo,
  bannerSelect,
  getShowType,
  setShowType,
  getShenyeBackground,
  setShenyeBackground,
} from '@/api/incentiveManagement/adConfigNew'

export default {
  components: {
    Loading
  },
  props: {
    visible: Boolean,
    id: String,
    pathType: String,
  },
  data() {

    return {
      title: '新增轮播图',
      switchModel: '1',//开启轮播图或者背景图 1 轮播图 2 背景图
      activeName: '1', //1 轮播图 2 背景图
      bjId: '',//背景图Id
      loading: false,
      roleList: [],
      imgLoading: false,
      appList_1: [],
      appList_2: [],
      appList_3: [],
      appList_4: [],
      appList_12: [],
      appList_13: [],
      appList_15: [],
      appTypeList: [],
      bjRuleForm: {
        bjImgUrl: '',//背景图
      },
      ruleForm: {
        advertisePageType: 1,//广告页面 1 神椰页面 2 神椰乐园
        bannerList: [
          {
            bannerName: '',//轮播图名称
            appId: '',//
            imgUrl: '',//图片url
            isShow: '1',//是否显示 1 显示 2 不显示
            redirectType: '1',//链接类型（1 神椰 2 H5 3 小程序）
            redirectUrl: '',//指定跳转链接
            wxRedirectUrl:'',//神椰小程序跳转地址
            appRedirectType: '', //APP跳转类型 1打卡活动 2打卡店铺 3神椰NFR 4盲盒活动 5神椰集市 6神椰工厂 7我的邀请码	
            appRedirectId: '', //APP跳转业务id
            appRedirectIdList: [],
          },
        ],
      },
      rules: {
        bannerName: [
          { required: true, message: '请填写轮播图名称', trigger: 'blur' }
        ],
        isShow: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        imgUrl: [
          { required: true, message: '请上传图片', trigger: 'change' }
        ],
        appId: [
          { required: true, message: '请填写appId', trigger: 'blur' }
        ],
        punchActivityId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        redirectType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        redirectUrl: [
          { required: true, message: '请填写链接', trigger: 'blur' }
        ],
        wxRedirectUrl: [
          { required: true, message: '请填写链接', trigger: 'blur' }
        ],
        bannerName: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        appRedirectType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        appRedirectId: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        bjImgUrl: [
          { required: true, message: '请上传背景图', trigger: 'change' }
        ],
      }
    }
  },
  computed: {

  },
  created() {
    this.getadminDict()
    this.getAppSelect(1)
    this.getAppSelect(2)
    this.getAppSelect(3)
    this.getAppSelect(4)
    this.getAppSelect(12)
    this.getAppSelect(13)
    this.getAppSelect(15)
    this.getShowType()
    this.ruleForm.id = this.id
    if (this.pathType == 'add') {
      this.title = '新增'
    } else {
      this.title = '编辑'
      setTimeout(()=>{
        this.getDatail()
      },50)
    }
    this.getShenyeBackground()
  },
  methods: {
    handleClick(tab, event) {
      console.log(tab, event);
    },
    init() {
      this.ruleForm.punchActivityId = ''//打卡活动id
      this.ruleForm.sort = ''
    },
    //获取展示轮播图或者背景图  1 轮播图 2 背景图
    getShowType() {
      const params = {};
      getShowType(params).then((res) => {
        this.switchModel = res.result
        this.activeName = res.result
        // if (res.result == '2') {
        //   this.getShenyeBackground()
        // } else {
        //   this.getDatail()
        //   this.getadminDict()
        //   this.getAppSelect(1)
        //   this.getAppSelect(2)
        //   this.getAppSelect(3)
        //   this.getAppSelect(4)
        //   this.getAppSelect(12)
        // }
      });
    },
    // 设置展示轮播图或者背景图 1 轮播图 2 背景图
    bannerSetShowType(showType) {
      setShowType(showType).then((res) => {
        this.$message.success('设置成功');
        this.getShowType()
        this.$emit('success')
      });
    },
    //获取背景图
    getShenyeBackground() {
      getShenyeBackground().then((res) => {
        this.bjId = res.result.id
        this.bjRuleForm.bjImgUrl = res.result.imgUrl
      });
    },
    //上传背景图片
    getBjImg(e) {
      this.bjRuleForm.bjImgUrl = e
      this.$refs['bjImgUrlRef'].clearValidate();
    },
    submitFormBj(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          var data = {
            id: this.bjId,
            imgUrl: this.bjRuleForm.bjImgUrl
          }
          setShenyeBackground(data).then(res => {
            setTimeout(() => {
              this.$message.success('设置成功')
              this.handleClose()
              this.$emit('success')
              this.loading = false
            }, 1000);
          }).catch(() => {
            this.loading = false
          }).finally(() => {

          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //获取字典值
    getadminDict() {
      const params = {
        dictType: "app_redirect_type",
      };
      adminDict(params).then((res) => {
        this.appTypeList = res.result[0].dictList
      });
    },

    //app跳转活动
    getAppSelect(type) {
      var data = {
        appRedirectType: type
      }
      bannerSelect(data).then(res => {
        if (type == 1) {
          this.appList_1 = res.result
        } else if (type == 2) {
          this.appList_2 = res.result
        } else if (type == 3) {
          this.appList_3 = res.result
        } else if (type == 4) {
          this.appList_4 = res.result
        } else if (type == 12) {
          this.appList_12 = res.result
        } else if (type == 13) {
          this.appList_13 = res.result
        }else if (type == 15) {
          this.appList_15 = res.result
        }
      })
    },
    changAppRedirectType(val, index) {
      // console.log('val', val)
      // console.log('index', index)
      if (this.ruleForm.bannerList[index].appRedirectId) {
        this.ruleForm.bannerList[index].appRedirectId = null
      }
      if (val == 1) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_1
      } else if (val == 2) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_2
      } else if (val == 3) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_3
      } else if (val == 4) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_4
      } else if (val == 12) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_12
      }else if (val == 13) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_13
      }else if (val == 15) {
        this.ruleForm.bannerList[index].appRedirectIdList = this.appList_15
      }

    },
    //获取轮播图详情
    getDatail() {
      bannerInfo(1).then(res => {
        this.ruleForm = res.result
        this.ruleForm.bannerList = this.ruleForm.bannerList.map((item, index) => {
          if (item.appRedirectType == 1) {
            item.appRedirectIdList = this.appList_1
          } else if (item.appRedirectType == 2) {
            item.appRedirectIdList = this.appList_2
          } else if (item.appRedirectType == 3) {
            item.appRedirectIdList = this.appList_3
          } else if (item.appRedirectType == 4) {
            item.appRedirectIdList = this.appList_4
          } else if (item.appRedirectType == 12) {
            item.appRedirectIdList = this.appList_12
          }else if (item.appRedirectType == 13) {
            item.appRedirectIdList = this.appList_13
          }else if (item.appRedirectType == 15) {
            item.appRedirectIdList = this.appList_15
          }
          return item
        })
      })
    },
    /** logo */
    getImg(e) {
      this.ruleForm.img = e
      this.$refs['imgRef'].clearValidate();
    },
    //新建
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.loading = true
          var data = {
            ...this.ruleForm
          }
          editBanner(data).then(res => {
            setTimeout(() => {
              this.$message.success('修改成功')
              this.handleClose()
              this.$emit('success')
              this.loading = false
            }, 1000);
          }).catch(() => {
            this.loading = false
          }).finally(() => {

          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    //取消
    handleClose(formName) {
      this.$emit('update:visible', false)
      // this.$refs[formName].resetFields();
    },
    //确认
    handleConfirm() {
      this.$emit('success', '你好')
    },
    handleSuccess(msg) {
      if (msg === '已拒绝') {
        var type = 'error'
      } else {
        var type = 'success'
      }
      this.$message({
        message: msg,
        type: type,
        duration: 1500,
        onClose: () => {
          this.handleClose()
          this.$emit('success')
        }
      })
    },
    //新增轮播图
    handleAdd() {
      var obj = {
        appId: '',//
        imgUrl: '',//图片url
        isShow: '1',//是否显示 1 显示 2 不显示
        bannerName: '',//轮播图名称
        redirectType: '',//链接类型（1 神椰 2 H5 3 小程序）
        redirectUrl: '',//指定跳转链接
        wxRedirectUrl:'',//神椰小程序跳转地址
      }
      this.ruleForm.bannerList.push(obj)
    },
    //删除轮播图
    handleDelete(ind) {
      this.ruleForm.bannerList.splice(ind, 1)
    },
    //轮播图广告上传图片
    getBannerImg(e, index) {
      this.ruleForm.bannerList[index].imgUrl = e
    },
    //上传图片
    getImg(e) {
      this.ruleForm.imgUrl = e
      this.$refs['imgRef'].clearValidate();
    },
    //上移一位
    upGo(index) {
      // console.log('index', index)
      var arr = this.ruleForm.bannerList
      if (index != 0) {
        // console.log(arr.splice(index - 1, 1, arr[index][0]))
        this.ruleForm.bannerList[index] = arr.splice(index - 1, 1, arr[index])[0]
        // console.log('arr', arr)
      } else {
        this.ruleForm.bannerList.push(arr.shift())
      }
    },
    //下移一位
    downGo(index) {
      var arr = this.ruleForm.bannerList
      if (index != arr.length - 1) {
        this.ruleForm.bannerList[index] = arr.splice(index + 1, 1, arr[index])[0]
      } else {
        this.ruleForm.bannerList.unshift(arr.splice(index, 1)[0])
      }
    }

  }
}
</script>
<style lang="scss" scoped>
.ex-diolog {
  ::v-deep .ex--dialog--footer {
    border: none !important;
    padding: 0 !important;
  }

  ::v-deep .ex--dialog--main {
    padding: 10px 20px !important;
  }
}

::v-deep .avatar-uploader2 .el-upload {
  width: 100% !important;
}

.avatar-uploader2 {
  width: 130px;
  height: 130px;
  text-align: center;
  line-height: 130px;
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
}

.banner_img {
  width: 130px;
  height: 130px;
}

.el-input {
  width: 300px;
}

.lable_l {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 20px 0 20px 80px;

  .left {
    margin-right: 20px;
  }
}

.bannerBox {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  .rig_btn_box {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    width: 100px;
    height: 200px;

    .el-button {
      margin: 0;
    }
  }
}

.imgBox {
  border: 1px solid #f5f5f5;
  border-radius: 12px;
  padding: 20px;
  width: 800px;

  .name {
    font-size: 16px;
    color: #606266;
    margin-bottom: 10px;
    padding-left: 50px;
  }
}
</style>